package cool.doudou.doudada.cipher.algorithm.util;

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import java.nio.charset.StandardCharsets;
import java.security.Security;

/**
 * Sm3Util
 *
 * @author jiangcs
 * @since 2022/08/31
 */
public class Sm3Util {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * Hash
     *
     * @param plaintext 明文
     * @return 16进制加密字符串
     */
    public static String hash(String plaintext) {
        return ByteUtils.toHexString(hash(plaintext.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * hmac
     *
     * @param plaintext  明文
     * @param encryptKey 加密Key
     * @return 16进制加密字符串
     */
    public static String hmac(String plaintext, String encryptKey) {
        return ByteUtils.toHexString(hmac(plaintext.getBytes(StandardCharsets.UTF_8), encryptKey.getBytes(StandardCharsets.UTF_8)));
    }

    private static byte[] hash(byte[] srcData) {
        SM3Digest digest = new SM3Digest();
        digest.update(srcData, 0, srcData.length);
        byte[] hash = new byte[digest.getDigestSize()];
        digest.doFinal(hash, 0);
        return hash;
    }

    private static byte[] hmac(byte[] key, byte[] srcData) {
        KeyParameter keyParameter = new KeyParameter(key);
        SM3Digest digest = new SM3Digest();
        HMac mac = new HMac(digest);
        mac.init(keyParameter);
        mac.update(srcData, 0, srcData.length);
        byte[] result = new byte[mac.getMacSize()];
        mac.doFinal(result, 0);
        return result;
    }
}
